package com.services;

import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.logging.Logger;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.jboss.resteasy.logging.impl.Log4jLogger;
import org.primefaces.component.log.Log;

import model.User;

import com.Constants;
import com.factory.Util;

@Stateless
public class UserService {
	@PersistenceContext(unitName = "cinema-unit")
	private EntityManager em;

	public void createUser(User newUser) {
		em.persist(newUser);
	}

	/**
	 * returns User object if username and password match
	 * 
	 * @param username
	 * @param password
	 * @return
	 */
	public User authenticate(String username, String password) {

		User user = null;

		try {

			Query q = em.createNamedQuery("authenticate");
			q.setParameter(Constants.USERNAME, username);

			q.setParameter("password", Util.getPasswordHash(password));

			List<?> result = q.getResultList();

			user = (User) result.get(0);

		} catch (NoSuchAlgorithmException e) {

		} catch (IndexOutOfBoundsException e) {

			// TODO da se logva che nyama nameren user
		}

		return user;

	}

}